package com.newthread.android.bean.remoteBean;

import android.os.Environment;
import cn.bmob.v3.BmobUser;
import com.bmob.BTPFileResponse;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadListener;
import com.newthread.android.activity.main.MyApplication;
import com.newthread.android.util.FileUtil;
import com.newthread.android.util.Loger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jindongping on 15/5/29.
 */
public class StudentUser extends BmobUser {
    private static final String LOGIN_URL = "http://ids.scuec.edu.cn/amserver/UI/Login?goto=http://my.scuec.edu.cn/index.portal";
    private static final String CHECK_URL = "http://ssfw.scuec.edu.cn/ssfw/j_spring_ids_security_check";
    private static final String INFO_URL = "http://ssfw.scuec.edu.cn/ssfw/navmenu.do";
    private static final String PHOTO_URL = "http://ssfw.scuec.edu.cn/ssfw/photo.widgets?handler=photo1Handler&value=&bh=";
    public static final String PHOTO_PATH = Environment.getExternalStorageDirectory() + "/personHeadPhoto.JPEG";
    private static final String INFO_CHECK_URL = "http://ssfw.scuec.edu.cn/ssfw/selectrange.widgets";

    private int id;

    private String name;
    private String sex;//性别
    private Integer age;


    private String qq;
    private String weiXin;
    private String mobPhone;

    private String brithDay;//生日
    private String province;//省份
    private String iDNumber;//证件号
    private String iDtype;//证件类型
    private String politicsStatus;//政治面貌
    private String nation;//民族
    private String departMent;//院系
    private String marjar;//专业
    private String nianji;//年级
    private String classNumber;//班级号
    private String from;//来自哪里
    private String liveAddress;//宿舍

    private String headPhotoName;
    private String headPhotoUrl;    //sdk给定加密地址
    private String headRealPhotoUrl;//解密后的实际头像地址
    private String passWord2;

    /**
     * @param userName 学号 由于BmobUser默认为 userName 所以只能指定userName为学号
     * @param passWord 密码
     */
    public StudentUser(String userName, String passWord) {
        setTableName("User");
        setUsername(userName);
        this.passWord2 = passWord;
        setPassword(passWord);
    }

    public void fitStudentInfoFromSchool(final OnSetInfoListner onSetInfoListner) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //当从图片上传完成后 回调出去
                    getStuentINFOFormShcoolWeb(getUsername(), getPassword(), onSetInfoListner);
                } catch (IOException e) {
                    onSetInfoListner.callBack("fail获取用户信息:" + e.toString());
                    e.printStackTrace();
                }

            }
        }).start();

    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getWeiXin() {
        return weiXin;
    }

    public void setWeiXin(String weiXin) {
        this.weiXin = weiXin;
    }

    public String getMobPhone() {
        return mobPhone;
    }

    public void setMobPhone(String mobPhone) {
        this.mobPhone = mobPhone;
    }

    public String getBrithDay() {
        return brithDay;
    }

    public void setBrithDay(String brithDay) {
        this.brithDay = brithDay;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getiDNumber() {
        return iDNumber;
    }

    public void setiDNumber(String iDNumber) {
        this.iDNumber = iDNumber;
    }

    public String getiDtype() {
        return iDtype;
    }

    public void setiDtype(String iDtype) {
        this.iDtype = iDtype;
    }

    public String getPoliticsStatus() {
        return politicsStatus;
    }

    public void setPoliticsStatus(String politicsStatus) {
        this.politicsStatus = politicsStatus;
    }

    public String getNation() {
        return nation;
    }

    public void setNation(String nation) {
        this.nation = nation;
    }

    public String getDepartMent() {
        return departMent;
    }

    public void setDepartMent(String departMent) {
        this.departMent = departMent;
    }

    public String getMarjar() {
        return marjar;
    }

    public void setMarjar(String marjar) {
        this.marjar = marjar;
    }

    public String getClassNumber() {
        return classNumber;
    }

    public void setClassNumber(String classNumber) {
        this.classNumber = classNumber;
    }

    public String getNianji() {
        return nianji;
    }

    public void setNianji(String nianji) {
        this.nianji = nianji;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getHeadRealPhotoUrl() {
        return headRealPhotoUrl;
    }

    public void setHeadRealPhotoUrl(String headRealPhotoUrl) {
        this.headRealPhotoUrl = headRealPhotoUrl;
    }

    public String getLiveAddress() {
        return liveAddress;
    }

    public void setLiveAddress(String liveAddress) {
        this.liveAddress = liveAddress;
    }

    public String getPassWord2() {
        return passWord2;
    }

    public void setPassWord2(String passWord2) {
        this.passWord2 = passWord2;
    }

    public String getHeadPhotoName() {
        return headPhotoName;
    }

    public String getHeadPhotoUrl() {
        return headPhotoUrl;
    }

    public void setHeadPhotoUrl(String headPhotoUrl) {
        this.headPhotoUrl = headPhotoUrl;
    }

    public void setHeadPhotoName(String headPhotoName) {
        this.headPhotoName = headPhotoName;
    }

    private void getStuentINFOFormShcoolWeb(String studentId, String passWord, OnSetInfoListner onSetInfoListner) throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        //登陆
        HttpPost httpPost = new HttpPost(LOGIN_URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("IDToken1", studentId));
        nvps.add(new BasicNameValuePair("IDToken2", passWord));
        nvps.add(new BasicNameValuePair("encoded", "true"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        consume(entity);
        //验证登陆
        HttpGet httpGet = new HttpGet(CHECK_URL);
        HttpResponse response1 = httpclient.execute(httpGet);
        HttpEntity entity1 = response1.getEntity();
        consume(entity1);
        //获取更多个人信息
        HttpPost httpPost1 = new HttpPost(INFO_URL);
        List<NameValuePair> nvps1 = new ArrayList<NameValuePair>();
        nvps1.add(new BasicNameValuePair("menuItemWid", "059ABDE77F985327E0502AD24B9F2A5E"));
        httpPost1.setEntity(new UrlEncodedFormEntity(nvps1));
        HttpResponse response2 = httpclient.execute(httpPost1);
        HttpEntity entity2 = response2.getEntity();
        String result2 = EntityUtils.toString(entity2);
        //解析个人信息 保存上传个人图片 成功后回调出去保存个人信息
        parseMoreInfo(result2, httpclient, onSetInfoListner);
        consume(entity2);
    }

    private void upLoadHeadPhoto(String photoPath, final OnSetInfoListner onSetInfoListner) {
        BTPFileResponse response = BmobProFile.getInstance(MyApplication.getInstance()).upload(photoPath, new UploadListener() {

            @Override
            public void onSuccess(String fileName, String url) {
                setHeadPhotoName(fileName);
                setHeadPhotoUrl(url);
                onSetInfoListner.callBack("sucess获取用户信息");

            }

            @Override
            public void onProgress(int ratio) {
            }

            @Override
            public void onError(int statuscode, String errormsg) {
            }
        });
    }

    private void parseMoreInfo(String result2, HttpClient httpclient, OnSetInfoListner onSetInfoListner) {
        try {
            List<NameValuePair> nvps = new ArrayList<>();
            Document document = Jsoup.parse(result2);
            //性别

            String xbdm = document.select("input[basetype=xbdm]").get(0).attr("value");
            nvps.add(new BasicNameValuePair("baseTypes", "xbdm"));
            nvps.add(new BasicNameValuePair("values", xbdm));
            nvps.add(new BasicNameValuePair("keys", "1"));
            //省份
            String xzqh = document.select("input[basetype=xzqh]").get(0).attr("value");
            nvps.add(new BasicNameValuePair("baseTypes", "xzqh"));
            nvps.add(new BasicNameValuePair("values", xzqh));
            nvps.add(new BasicNameValuePair("keys", "2"));
            //证件类型
            String zjlx = document.select("input[basetype=zjlx]").get(0).attr("value");
            nvps.add(new BasicNameValuePair("baseTypes", "zjlx"));
            nvps.add(new BasicNameValuePair("values", zjlx));
            nvps.add(new BasicNameValuePair("keys", "3"));
            //政治面貌
            String zzmm = document.select("input[basetype=zzmm]").get(0).attr("value");
            nvps.add(new BasicNameValuePair("baseTypes", "zzmm"));
            nvps.add(new BasicNameValuePair("values", zzmm));
            nvps.add(new BasicNameValuePair("keys", "4"));
            //民族
            String mzdm = document.select("input[basetype=mzdm]").get(0).attr("value");
            nvps.add(new BasicNameValuePair("baseTypes", "mzdm"));
            nvps.add(new BasicNameValuePair("values", mzdm));
            nvps.add(new BasicNameValuePair("keys", "5"));
            //年级
            String njdm = document.select("input[basetype=njdm]").get(0).attr("value");
            nvps.add(new BasicNameValuePair("baseTypes", "njdm"));
            nvps.add(new BasicNameValuePair("values", njdm));
            nvps.add(new BasicNameValuePair("keys", "6"));
            //学院
            String dwdm = document.select("input[basetype=dwdm]").get(0).attr("value");
            nvps.add(new BasicNameValuePair("baseTypes", "dwdm"));
            nvps.add(new BasicNameValuePair("values", dwdm));
            nvps.add(new BasicNameValuePair("keys", "7"));
            //专业
            String zydm = document.select("input[basetype=zydm]").get(0).attr("value");
            nvps.add(new BasicNameValuePair("baseTypes", "zydm"));
            nvps.add(new BasicNameValuePair("values", zydm));
            nvps.add(new BasicNameValuePair("keys", "8"));
            //家庭地址
            String xzqh_more = document.select("input[basetype=xzqh]").get(1).attr("value");
            nvps.add(new BasicNameValuePair("baseTypes", "xzqh"));
            nvps.add(new BasicNameValuePair("values", xzqh_more));
            nvps.add(new BasicNameValuePair("keys", "9"));

            //名字
            String name = document.select("input[name=xm]").get(0).attr("value");
            setName(name);
            //生日
            String brithday = document.select("input[name=csrq]").get(0).attr("value");
            setBrithDay(brithday);
            //证件号
            String iDNumber = document.select("input[name=zjh]").get(0).attr("value");
            setiDNumber(iDNumber);
            //宿舍
            String livingRom = document.select("input[name=ssmc]").get(0).attr("value");
            setLiveAddress(livingRom);
            //班级
            String classNumber = document.select("input[name=bjh]").get(0).attr("value");
            setClassNumber(classNumber);

            HttpPost httpPost = new HttpPost(INFO_CHECK_URL);
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            if (result.contains("男")) {
                setSex("男");
            } else {
                setSex("女");
            }

            JSONArray jsonArray = new JSONArray(result);
            try {
                setProvince(jsonArray.getJSONObject(1).getString("label"));
            }catch (Exception e){
                Loger.V("得到的省份为空");
            }
            try {
                setiDtype(jsonArray.getJSONObject(2).getString("label"));
            }catch (Exception e){
                Loger.V("得到得的ID类型为空");
            }
            try {
                setPoliticsStatus(jsonArray.getJSONObject(3).getString("label"));
            }catch (Exception e){
                Loger.V("得到政治面貌为空");
            }
            try {
                setNation(jsonArray.getJSONObject(4).getString("label"));
            }catch (Exception e){
                Loger.V("得到民族为空");
            }
            try {
                setNianji(jsonArray.getJSONObject(5).getString("label"));
            }catch (Exception e){
                Loger.V("得到年级为空");
            }
            try {
                setDepartMent(jsonArray.getJSONObject(6).getString("label"));
            }catch (Exception e){
                Loger.V("得到部门为空");
            }
            try {
                setMarjar(jsonArray.getJSONObject(7).getString("label"));
            }catch (Exception e){
                Loger.V("得到专业为空");
            }
            try {
                setFrom(jsonArray.getJSONObject(8).getString("label"));
            }catch (Exception e){
                Loger.V("得到来自哪里为空");
            }
            consume(entity);


            //保存个人图片
            HttpGet photoGet = new HttpGet(PHOTO_URL + getUsername());
            HttpResponse photoResponse = httpclient.execute(photoGet);
            HttpEntity photoEntity = photoResponse.getEntity();
            FileUtil.saveImage(photoEntity, PHOTO_PATH);
            consume(photoEntity);

            //上传头像，并设置头像名字（唯一）
            upLoadHeadPhoto(PHOTO_PATH, onSetInfoListner);

        } catch (Exception e) {
            Loger.V("有可能账号密码错误");
        }

    }

    public interface OnSetInfoListner {

        void callBack(String result);
    }

    private void consume(final HttpEntity entity) throws IOException {
        if (entity == null) {
            return;
        }
        if (entity.isStreaming()) {
            InputStream instream = entity.getContent();
            if (instream != null) {
                instream.close();
            }
        }
    }

    @Override
    public String toString() {
        return "StudentUser{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", qq='" + qq + '\'' +
                ", weiXin='" + weiXin + '\'' +
                ", mobPhone='" + mobPhone + '\'' +
                ", brithDay='" + brithDay + '\'' +
                ", province='" + province + '\'' +
                ", iDNumber='" + iDNumber + '\'' +
                ", iDtype='" + iDtype + '\'' +
                ", politicsStatus='" + politicsStatus + '\'' +
                ", nation='" + nation + '\'' +
                ", departMent='" + departMent + '\'' +
                ", marjar='" + marjar + '\'' +
                ", nianji='" + nianji + '\'' +
                ", classNumber='" + classNumber + '\'' +
                ", from='" + from + '\'' +
                ", liveAddress='" + liveAddress + '\'' +
                '}';
    }
}
